package com.ilxqx.framework.system.upload.qiniu.service;

import com.ilxqx.framework.security.util.KeyUtils;
import com.ilxqx.framework.system.config.QiNiuConfigProperties;
import com.ilxqx.framework.system.config.UploadConfigProperties;
import com.ilxqx.framework.system.upload.qiniu.strategy.FrameworkUploadStrategy;
import com.ilxqx.framework.util.DateUtils;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 七牛图片上传服务类
 * @author venus
 */
@Service
@Slf4j
public class QiNiuImgUploadService extends AbstractQiNiuUploadService {

	private static final String RETURN_BODY = "{\"key\": $(key), \"hash\": $(etag)}";
	private final QiNiuConfigProperties qiNiuConfigProperties;
	private final UploadConfigProperties uploadConfigProperties;
	private final Auth auth;

	@Autowired
	public QiNiuImgUploadService(QiNiuConfigProperties qiNiuConfigProperties, UploadConfigProperties uploadConfigProperties, Auth auth) {
		this.qiNiuConfigProperties = qiNiuConfigProperties;
		this.uploadConfigProperties = uploadConfigProperties;
		this.auth = auth;
	}

	/**
	 * 生成上传凭证
	 *
	 * @return 上传凭证
	 */
	@Override
	public String generateUploadToken() {
		// 构建上传策略
		FrameworkUploadStrategy uploadStrategy = new FrameworkUploadStrategy();
		uploadStrategy.setScope(this.qiNiuConfigProperties.getBucket());
		uploadStrategy.setSaveKey(this.uploadConfigProperties.getImg().getPrefix() + KeyUtils.generateUUID());
		uploadStrategy.setDeadline(DateUtils.getUnixTime(DateUtils.localDateTimeToDate(LocalDateTime.now().plusHours(1L)).getTime()));
		uploadStrategy.setFsizeLimit(this.uploadConfigProperties.getImg().getMaxSize().toBytes());
		uploadStrategy.setReturnBody(RETURN_BODY);
		uploadStrategy.setCallbackUrl(this.qiNiuConfigProperties.getCallbackUrl() + this.uploadConfigProperties.getImg().getCallbackPath());
		uploadStrategy.setCallbackHost(this.qiNiuConfigProperties.getCallbackHost());
		uploadStrategy.setCallbackBodyType(MediaType.APPLICATION_JSON_VALUE);
		uploadStrategy.setCallbackBody(RETURN_BODY);
		uploadStrategy.setMimeLimit("image/*");
		return this.auth.uploadTokenWithPolicy(uploadStrategy);
	}

}
